package com.servlet;

import com.dao.MemberService;
import com.dao.impl.MemberServiceImpl;
import com.entity.Member;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.servlet.teacher.BaseServlet;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
import com.util.JsonUtil;
import com.util.PageUtil;
import com.util.ProxyUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.converters.SqlDateConverter;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author ly
 * @dATE 2022-03-23 17:02
 */
@WebServlet("/MemberServlet")
public class MemberServlet extends BaseServlet {
    MemberService memberDao = (MemberService) ProxyUtil.getDaoProxy(new MemberServiceImpl());
    /**
     * 查询所有数据
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
     public void queryList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        resp.setContentType("text/html;charset=utf-8");
        Member member = new Member();
        //当前页
        String currentPage = req.getParameter("currentPage");
        //获取每页显示的数量
        String pageSize = req.getParameter("pageSize");
        //查询条件
        String nickname = req.getParameter("nickname");

        member.setNickname(nickname);
        JsonUtil jsonUtil = new JsonUtil();
        try {
            PageUtil<Member> members = memberDao.queryDataBypage(Integer.parseInt(currentPage), Integer.parseInt(pageSize), member);

            jsonUtil.setCode(200);
            jsonUtil.setData(members);
        } catch (Exception e) {
            jsonUtil.setCode(500);
            jsonUtil.setMsg("系统错误");
            e.printStackTrace();
        }

        Gson gson = new Gson();
        String toJson = gson.toJson(jsonUtil);

        PrintWriter writer = resp.getWriter();
        writer.print(toJson);
    }

    /*
    * 查询
    */

    //删除单行
    public void deleteRow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        String id = req.getParameter("memberId");
        JsonUtil jsonUtil = new JsonUtil();
        try {
            int res = memberDao.deleteById(id);
            jsonUtil.setCode(200);
            jsonUtil.setMsg("成功");
        } catch (SQLException e) {
            jsonUtil.setCode(500);
            jsonUtil.setMsg("失败");
            e.printStackTrace();
        }
        Gson gson = new Gson();
        String toJson = gson.toJson(jsonUtil);

        PrintWriter writer = resp.getWriter();
        writer.print(toJson);
    }

    //批量删除
    public void deleteByIdS(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String ids = req.getParameter("ids");

        Gson gson = new Gson();
        JsonUtil jsonUtil = new JsonUtil();
        List<Object> o = gson.fromJson(ids, new TypeToken<List<Object>>(){}.getType());

        try {
            int i = memberDao.deleteByIdS(o);
            jsonUtil.setCode(200);
            jsonUtil.setMsg("成功");
        } catch (SQLException e) {
            e.printStackTrace();
            jsonUtil.setCode(1);
            jsonUtil.setMsg("失败");
        }
        String toJson = gson.toJson(jsonUtil);

        PrintWriter writer = resp.getWriter();
        writer.print(toJson);
    }

    /**
     * 查询密码
     */
    public void queryPassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        System.out.println("id为"+id);
        Member member = new Member();
        Gson gson = new Gson();
        JsonUtil jsonUtil = new JsonUtil();
        member.setMemberId(Integer.parseInt(id));

        try {
            List<Member> members = memberDao.queryPassword(member);
            System.out.println(members.size());
            jsonUtil.setCode(200);
            jsonUtil.setData(members.get(0).getPassword());
        } catch (Exception e) {
            jsonUtil.setCode(500);
            jsonUtil.setMsg("系统错误");
            e.printStackTrace();
        }
        String toJson = gson.toJson(jsonUtil);
        PrintWriter writer = resp.getWriter();
        writer.print(toJson);
    }

    // 修改
    public void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ConvertUtils.register(new SqlDateConverter(null), java.sql.Date.class);
        Member member = new Member();
        req.removeAttribute("birthday");

        //日期格式转换器yyyy-MM-dd转换成data类型(很重要)
        ConvertUtils.register(new DateLocaleConverter(),Date.class);

        Gson gson = new Gson();
        JsonUtil jsonUtil = new JsonUtil();

        PrintWriter writer = resp.getWriter();
        try {
            BeanUtils.populate(member,req.getParameterMap());

            List<Member> members = memberDao.queryData(member);
            // 检查修改为的用户名是否已存在
            if (members.size() != 0 && !members.get(0).getNickname().equals(member.getNickname())){
                jsonUtil.setCode(111);
                String str = gson.toJson(jsonUtil);
                writer.print(str);
                return;
            }

            memberDao.update(member);
            jsonUtil.setCode(200);
            jsonUtil.setMsg("成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonUtil.setCode(500);
            jsonUtil.setMsg("失败");
        }
        String toJson = gson.toJson(jsonUtil);
        writer.print(toJson);
    }

    // 增加
    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Member member = new Member();

        //日期格式转换器yyyy-MM-dd转换成data类型(很重要)
        ConvertUtils.register(new DateLocaleConverter(),Date.class);

        Gson gson = new Gson();
        JsonUtil jsonUtil = new JsonUtil();
        PrintWriter writer = resp.getWriter();
        try {
            BeanUtils.populate(member,req.getParameterMap());
            // 对将要添加的用户名查询，检查是否存在
            List<Member> members = memberDao.queryData(member);
            if (members.size() != 0){
                jsonUtil.setCode(111);
                String str = gson.toJson(jsonUtil);
                writer.print(str);
                return;
            }
            memberDao.insert(member);
            jsonUtil.setCode(200);
            jsonUtil.setMsg("成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonUtil.setCode(500);
            jsonUtil.setMsg("失败");
        }
        String toJson = gson.toJson(jsonUtil);


        writer.print(toJson);
    }
    //重置密码
    public void resetPassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Gson gson = new Gson();
        JsonUtil jsonUtil = new JsonUtil();
        String memberId = req.getParameter("memberId");
        try {
            memberDao.resetPassword(Integer.parseInt(memberId));
            jsonUtil.setCode(200);
            jsonUtil.setMsg("成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonUtil.setCode(500);
            jsonUtil.setMsg("失败");
        }

        String toJson = gson.toJson(jsonUtil);

        PrintWriter writer = resp.getWriter();
        writer.print(toJson);
    }
}
